package Test1;

import java.io.*;
import java.util.List;

/**
 * 文件工具类，负责文件的读写操作
 * 支持TXT和CSV格式输出
 */
public class FileUtil {

    /**
     * 将表达式列表保存到TXT文件
     */
    public static void saveToTxtFile(List<Expression> expressions, String filename,
                                     boolean withAnswers, int columns) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(filename))) {
            for (int i = 0; i < expressions.size(); i++) {
                Expression expr = expressions.get(i);
                String line;
                if (withAnswers) {
                    line = (i + 1) + ". " + expr.toStringWithAnswer();
                } else {
                    line = (i + 1) + ". " + expr.toString();
                }

                writer.print(line);

                // 控制列数
                if ((i + 1) % columns == 0) {
                    writer.println();
                } else {
                    writer.print("\t\t");
                }
            }
            System.out.println("题目已保存到TXT文件: " + filename);
        } catch (IOException e) {
            System.out.println("保存TXT文件时出错: " + e.getMessage());
        }
    }

    /**
     * 将表达式列表保存到CSV文件
     */
    public static void saveToCSVFile(List<Expression> expressions, String filename,
                                     boolean withAnswers, int columns) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(filename))) {
            // CSV表头
            if (withAnswers) {
                writer.println("题目,答案");
            } else {
                writer.println("题目");
            }

            for (int i = 0; i < expressions.size(); i++) {
                Expression expr = expressions.get(i);
                writer.print(expr.toCSV(withAnswers));

                // 控制列数（CSV中每行多个题目）
                if ((i + 1) % columns == 0) {
                    writer.println();
                } else if (i < expressions.size() - 1) {
                    writer.print(",");
                }
            }
            System.out.println("题目已保存到CSV文件: " + filename);
        } catch (IOException e) {
            System.out.println("保存CSV文件时出错: " + e.getMessage());
        }
    }

    /**
     * 读取文件内容
     */
    public static void readFile(String filename) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            System.out.println("文件内容:");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("读取文件时出错: " + e.getMessage());
        }
    }
}